package com.UdpRecieve.framework.utils;


import com.UdpRecieve.tool.SpringUtils;
import com.UdpRecieve.domain.system.SysUser;
import com.UdpRecieve.framework.constant.ServletConstant;
import com.UdpRecieve.mapper.SysUserMapper;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

/**
 * 客户端工具类
 * 
 * @author ruoyi
 */
public class ServletUtils
{
    /**
     * 获取String参数
     */
    public static String getParameter(String name)
    {
        return String.valueOf(getRequest().getParameter(name));
    }


    /**
     * 获取Integer参数
     */
    public static Integer getParameterToInt(String name)
    {
        return Integer.valueOf(getRequest().getParameter(name));
    }



    /**
     * 获取request
     */
    public static HttpServletRequest getRequest()
    {
        return getRequestAttributes().getRequest();
    }

    /**
     * 获取response
     */
    public static HttpServletResponse getResponse()
    {
        return getRequestAttributes().getResponse();
    }

    /**
     * 获取session
     */
    public static HttpSession getSession()
    {
        return getRequest().getSession();
    }

    public static ServletRequestAttributes getRequestAttributes()
    {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        return (ServletRequestAttributes) attributes;
    }

    /**
     * 将字符串渲染到客户端
     * 
     * @param response 渲染对象
     * @param string 待渲染的字符串
     * @return null
     */
    public static String renderString(HttpServletResponse response, String string)
    {
        try
        {
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(string);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }

    public static SysUser getOnlineUser(){
        SysUser sysUser = new SysUser();

        String sessionId = getRequest().getSession().getId();
        for(Map.Entry<String,String> entry: ServletConstant.OnlineUserList.entrySet()){
            if (entry.getValue().equals(sessionId)){
                String loginName =  entry.getKey();
                sysUser.setUserName(loginName);
                SysUserMapper sysUserMapper = SpringUtils.getBean(SysUserMapper.class);
                sysUser = sysUserMapper.selectUser(sysUser).get(0);
            }
        }
        return sysUser;
    }
}
